using UnityEngine;
using UnityEngine.Events;

public class Tracer : MonoBehaviour
{
    public Transform aim,target;
    public Vector2 localPosition;
    public float distanceLimit = 1.5f;
    public GameObject succeed, error;
    public bool overLimit;
    public UnityEvent<Vector2> PositionUpdate;    
    public UnityEvent<bool> OverDistanceLimitEvent;
    public UnityEvent<bool> StateChangedEvent;

    private void Start()
    {
        InitState();
    }

    void Update()
    {
        if(aim != null && target != null)
        {
            CheckState();
            PositionUpdate?.Invoke(localPosition);            
            OverDistanceLimitEvent?.Invoke(overLimit);
            succeed.SetActive(!overLimit);
            error.SetActive(overLimit);
        }
    }

    void CheckState()
    {
        localPosition = aim.InverseTransformPoint(target.position);
        bool newState = localPosition.magnitude > distanceLimit;
        if (newState != overLimit)
        {
            overLimit = newState;
            StateChangedEvent?.Invoke(overLimit);
        }
    }

    void InitState()
    {
        localPosition = aim.InverseTransformPoint(target.position);
        overLimit = localPosition.magnitude > distanceLimit;
        StateChangedEvent?.Invoke(overLimit);
    }
}
